package com.hnxxxy.common.shiro;
import com.hnxxxy.sysmgr.pojo.Staff;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;


@Setter
@Slf4j
public class MyShiroCache implements Cache{

    private String name;// 权限缓存的标识
    private RedisTemplate<String,Object> templateRedis;
    public MyShiroCache(){}
    public MyShiroCache(String name) {// 在CacheManager中会调用此方法
        /*log.info("Shiro Cache Name:"+name);*/
        this.name = name;
    }
    /**
     * todo: 检查缓存，以用户凭证为key
     * @param o =key=用户凭证 ~= 对象
     * @return
     * @throws CacheException
     */
    @Override
    public Object get(Object o) throws CacheException {
        SimplePrincipalCollection  collection=(SimplePrincipalCollection)o;
        Staff staff= (Staff) collection.getPrimaryPrincipal();
        Object data = templateRedis.opsForValue().get(staff.getLoginname());
        if (data == null) {
            log.info("-->权限信息，检查缓存，没有找到");
            return null;
        }
        log.info("-->权限信息，检查缓存，找到了");
        return data;
    }

    /**
     * todo: 将从数据库中查询出的该用户的权限信息 存入缓存(redis)
     * @param o =key=用户凭证 ~= 对象
     * @param o2 = 权限数据
     * @return
     * @throws CacheException
     */
    @Override
    public Object put(Object o, Object o2) throws CacheException {
        SimplePrincipalCollection  collection=(SimplePrincipalCollection)o;
        Staff staff= (Staff) collection.getPrimaryPrincipal();
        log.info("-->存Shrio Cache:"+staff.getLoginname());
        templateRedis.opsForValue().set(staff.getLoginname(),o2);
        return null;
    }

    /**
     * todo: 可以移除某个用户的权限信息的缓存，用于 subject.logout();
     * @param o =key=用户凭证 ~= 对象
     * @return
     * @throws CacheException
     */
    @Override
    public Object remove(Object o) throws CacheException {
        SimplePrincipalCollection  collection=(SimplePrincipalCollection)o;
        Staff staff= (Staff) collection.getPrimaryPrincipal();
        log.info("-->删除Shrio Cache:"+staff.getLoginname());
        templateRedis.delete(staff.getLoginname());
        return null;
    }

    @Override
    public void clear() throws CacheException {
        log.info("-->删除Shrio Cache所有");
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public Set keys() {
        return null;
    }

    @Override
    public Collection values() {
        return null;
    }
}
